import { getInfo, getToken, logout, refreshToken, getTokenByZyToken } from '@/api/login'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Cookie from 'js-cookie'

const user = {
  state: {
    token: '',
    name: '',
    userId: '',
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      if (token) {
        Cookie.set(ACCESS_TOKEN, token)
      }
    },
    SET_NAME: (state, { name }) => {
      state.name = name
    },
    SET_USER_ID: (state, userId) => {
      state.userId = userId
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    RefreshToken ({ commit, getters }) {
      if (!Cookie.get('REFRESH_TOKEN')) {
        return clearAndLogin({ commit, getters })
      }
      return new Promise((resolve, reject) => {
        const params = {
          refreshToken: Cookie.get('REFRESH_TOKEN'),
          terminal: 1
        }
        refreshToken(params)
          .then((response) => {
            const result = response
            commit('SET_TOKEN', result)
            resolve(result)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取 ACCESS_TOKEN
    GetACCESS_TOKEN ({ commit }) {
      return new Promise((resolve, reject) => {
        const params = {
          code: window.sessionStorage.getItem('code'),
          terminal: 1
        }
        getToken(params)
          .then((response) => {
            const result = response
            commit('SET_TOKEN', result.token)
            Cookie.set('REFRESH_TOKEN', result.refreshToken)
            window.sessionStorage.removeItem('code')
            resolve()
          })
          .catch((error) => {
            window.sessionStorage.removeItem('code')
            reject(error)
          })
      })
    },
    // 换取一体化token
    GetZY_TOKEN ({ commit }, { portalToken, portalUid }) {
      return new Promise((resolve, reject) => {
        const params = {
          ddToken: portalToken,
          uid: portalUid
        }
        getTokenByZyToken(params)
          .then((response) => {
            const result = response
            console.log(response)
            commit('SET_TOKEN', result.token)
            Cookie.set('REFRESH_TOKEN', result.refreshToken)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    InitPortalInfo ({ state, commit, dispatch }, props) {
      return new Promise((resolve, reject) => {
        console.log(props)
        const { portalType } = props
        commit('SET_portalType', portalType)
        const portalInfo = props.getGlobalState()
        if (portalType === 'portalYth') {
          // 一体化平台访问
          const { portalToken, portalUid } = portalInfo
          dispatch('GetZY_TOKEN', { portalToken, portalUid })
            .then(() => {
              dispatch('GetInfo').then(() => {
                resolve()
              })
            })
            .catch(() => {
              dispatch('MfeLogout')
            })
        } else {
          // 自定义事件
          resolve()
        }
      })
    },
    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((response) => {
            const result = response

            commit('SET_INFO', result)
            commit('SET_USER_ID', result.userId)
            commit('SET_NAME', { name: result.name || result.userName })

            resolve(result)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    Login ({ commit, getters }) {
      return new Promise((resolve) => {
        clearAndLogin({ commit, getters })
        resolve()
      })
    },
    // 登出
    Logout ({ commit, getters, dispatch }) {
      return new Promise((resolve) => {
        if (window.__POWERED_BY_QIANKUN__) {
          dispatch('MfeLogout').then(() => {
            resolve()
          })
        } else {
          if (!getters.userInfo.userAccount) {
            clearAndLogout({ commit, getters })
            resolve()
          } else {
            logout({
              loginName: getters.userInfo.userAccount || '',
              terminal: 1
            })
              .then(() => {
                clearAndLogout({ commit, getters })
                resolve()
              })
              .catch(() => {
                resolve()
              })
          }
        }
      })
    },
    MfeLogout ({ commit, rootState, dispatch }) {
      return new Promise((resolve) => {
        const global = rootState.global
        const { portalType } = global
        if (portalType === 'portalYth') {
          dispatch('global/setGlobalState', { portalToken: '' })
        } else if (portalType === 'default') {
          dispatch('global/setGlobalState', { token: '' })
        }
        resolve()
      })
    }
  }
}
/**
 * 重定向 地址
 * return 认证登录 携带code返回
 */
const loginFn = (getters) => {
  // const clientId = getters.client_Id || window.config?.VUE_APP_CLIENT_ID
  const clientId = process.env.VUE_APP_CLIENT_ID
  const authentication = process.env.VUE_APP_AUTH_URL + '/idp/oauth2/authorize?client_id=' + clientId // 身份认证地址
  const redirect = window.location.href
  const redirectUrl = 'redirect_uri=' + encodeURIComponent(redirect) + '&response_type=code' // 重定向地址 -测试
  console.log(`${authentication}&${redirectUrl}`)
  window.location.href = `${authentication}&${redirectUrl}`
}

const logoutFn = (getters) => {
  // const clientId = getters.client_Id || window.config.VUE_APP_CLIENT_ID
  const clientId = process.env.VUE_APP_CLIENT_ID
  const authentication =
    process.env.VUE_APP_AUTH_URL + '/idp/profile/OAUTH2/Redirect/GLO?entityId=' + clientId// 身份认证地址
  const redirect = window.location.href
  const redirectUrl = 'redirctToUrl=' + encodeURIComponent(redirect) + '&redirectToLogin=true' // 重定向地址 -测试
  console.log(`${authentication}&${redirectUrl}`)
  window.location.replace(`${authentication}&${redirectUrl}`)
}

const clearAndLogin = ({ commit, getters }) => {
  commit('SET_TOKEN', '')
  commit('SET_INFO', {})
  commit('SET_USER_ID', [])
  commit('SET_NAME', '')
  storage.clearAll()
  Cookie.remove(ACCESS_TOKEN)
  Cookie.remove('REFRESH_TOKEN')
  window.sessionStorage.removeItem('code')
  loginFn(getters)
}

const clearAndLogout = ({ commit, getters }) => {
  commit('SET_TOKEN', '')
  commit('SET_INFO', {})
  commit('SET_USER_ID', [])
  commit('SET_NAME', '')
  storage.clearAll()
  Cookie.remove(ACCESS_TOKEN)
  Cookie.remove('REFRESH_TOKEN')
  window.sessionStorage.removeItem('code')
  logoutFn(getters)
}

export default user
